/**
 * Created by ZHOUSH on 12/24/2015.
 */
var summary = '26c34eaa50a87c080037c40f665a1f13_DATA';
var Promise = require('promise');
var fs = require('fs');
var pread = Promise.denodeify(fs.readFile);
var ptocsv = Promise.denodeify(require('csv').stringify);
var pwrite = Promise.denodeify(fs.writeFile);
var sutil = require('../util');
var plsql = require('../../tool/plsql-parser');
var _ = require('underscore');

var search = function (criteria) {
    return pread(__dirname + '/../file/data/' + summary, 'utf-8')
        .then(function (data) {
            data = JSON.parse(data);
            return data.filter(function (item) {
                var ret = true;
                for (var prop in criteria) {
                    if (criteria.hasOwnProperty(prop)) {
                        var val0 = criteria[prop];
                        var val1 = item[prop];
                        if (typeof val0 == 'object' && val0.exec) {
                            ret = ret && (val0.exec(val1));
                        } else if (typeof val0 == 'string') {
                            ret = ret && val1.indexOf(val0) >= 0
                        } else {
                            ret = ret && (val1 == val0)
                        }
                    }
                }
                return ret;
            });
        }, console.log);
};
var sql = function (key, type) {
    if (type != 'ORCL') {
        return pread(__dirname + '/../file/sql_summary.json', 'utf-8').then(function (data) {
            data = JSON.parse(data);
            return data.filter(function (item) {
                return item.key == key;
            })
        })
    } else {
        return pread(__dirname + '/../file/orcl_summary.json', 'utf-8').then(function (data) {
            data = JSON.parse(data);
            return data.filter(function (item) {
                return item.key == key;
            })
        })
    }
};
exports.search = search;
exports.sql = sql;
var init_module = function (app) {
    app.post('/api/rpt/search', function (req, res) {
        var param = req.body;
        var cri = {};
        for (var prop in param) {
            if (param.hasOwnProperty(prop) && prop != 'meta') {
                cri[prop] = param['meta']['regex'] ? new RegExp(param[prop]) : param[prop];
            }
        }
        search(cri).then(function (data) {
            if (!param['meta']['schedInfo']) {
                var props = ['RPT_NAME','RPT_TITLE','SYS_CODE','TYPE','CUST_NAME','CUST_CODE','KEY'];
                data = _.keys(_.groupBy(data, function (item) {
                    var obj = {};
                    props.forEach(function (prop) {
                        obj[prop] = item[prop];
                    });
                    return JSON.stringify(obj);
                })).map(JSON.parse);
            }
            if (param['meta']['download']) {
                return ptocsv(data, {
                    header: true
                }).then(function (final) {
                    res.attachment('Report Summary.csv');
                    res.setEncoding('utf-8');
                    res.end(final);
                });
            } else {
                res.json(data);
            }
        }, sutil.server_err(res, param));
    });
    app.post('/api/rpt/sql', function (req, res) {
        var param = req.body;
        sql(param.key, param.type).then(function (data) {
            res.json(data);
        }, sutil.server_err(res, param));
    });
    app.post('/api/rpt/parse/plsql', function (req, res) {
        var param = req.body;
        res.json(plsql.parseSql(param.sql));
    });
    app.get('/api/rpt/download', function (req, res) {
        var param = JSON.parse(req.query['criteria']);
        var cri = {};
        for (var prop in param) {
            if (param.hasOwnProperty(prop) && prop != 'meta') {
                cri[prop] = param['meta']['regex'] ? new RegExp(param[prop]) : param[prop];
            }
        }
        search(cri).then(function (data) {
            if (!param['meta']['schedInfo']) {
                var props = ['RPT_NAME','RPT_TITLE','SYS_CODE','TYPE','CUST_NAME','CUST_CODE','KEY'];
                data = _.keys(_.groupBy(data, function (item) {
                    var obj = {};
                    props.forEach(function (prop) {
                        obj[prop] = item[prop];
                    });
                    return JSON.stringify(obj);
                })).map(JSON.parse);
            }
            if (param['meta']['download']) {
                return ptocsv(data, {
                    header: true
                }).then(function (final) {
                    res.attachment('Report_Summary_' + (new Date()).getTime() + '.csv');
                    res.end(final);
                });
            } else {
                res.json(data);
            }
        }, sutil.server_err(res, param));
    })
};
exports.init_module = init_module;